package com.n.facedetectordemo;

import android.os.Environment;
import android.text.TextUtils;
import android.util.Log;

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.text.DecimalFormat;
import java.util.ArrayList;

/**
 * Title: FileUtils.java
 * Description: 对sd卡的文件相关操作
 *
 * @author Liusong
 * @version V1.0
 * @date 2015-1-12
 */
public class FileOpUtil {

    /**
     * 判断sdcrad是否已经安装
     *
     * @return boolean true安装 false 未安装
     */
    public static boolean isSDCardMounted() {
        return Environment.MEDIA_MOUNTED.equals(Environment.getExternalStorageState());
    }

    /**
     * 得到sdcard的路径
     *
     * @return
     */
    public static String getSDCardRoot() {
//		if(isSDCardMounted()){
//            String ppath = Environment.getExternalStorageDirectory().getAbsolutePath();
//
//            String path = ppath + "/Android/data/" + "com.n.facedetectordemo";
//            File file = new File(path);
//            if (file.exists()) {
//                return path;
//            } else {
//                return ppath;
//            }
//		}
        String ret = "data/data/" + BuildConfig.APPLICATION_ID  + "/files";
        return ret;
    }


    public static String getSDCardRoot4FaceSet() {
        String root = getSDCardRoot();
        String faceSet = root + "/faces";
        File file = new File(faceSet);
        if (!file.exists()) {
            if (file.mkdir()) {
                return faceSet;
            } else {
                return "";
            }
        }
        return faceSet;
    }


    public static String getSDCardRoot4FaceTemp() {
        String root = getSDCardRoot();
        String faceSet = root + "/temp";
        File file = new File(faceSet);
        if (!file.exists()) {
            if (file.mkdir()) {
                return faceSet;
            } else {
                return "";
            }
        }
        return faceSet;
    }

    /**
     * 把内容写入文件
     *
     * @param path 文件路径
     * @param text 内容
     */
    public static void write2File(String path, String text, boolean append) {
        BufferedWriter bw = null;
        try {
            //1.创建流对象
            bw = new BufferedWriter(new FileWriter(path, append));
            //2.写入文件
            bw.write(text);
            //换行刷新
            bw.newLine();
            bw.flush();

        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            //4.关闭流资源
            if (bw != null) {
                try {
                    bw.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    /**
     * 删除文件
     *
     * @param path
     * @return
     */
    public static boolean deleteFile(String path) {
        if (TextUtils.isEmpty(path)) {
            throw new RuntimeException("路径为空");
        }
        File file = new File(path);
        if (file.exists()) {
            try {
                file.delete();
                return true;
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return false;
    }

    public static void deleteDirAndFile(String path, String ignorePath) {
        Log.d(TAG, "deleteDirAndFile  " + path);

        if (!TextUtils.isEmpty(ignorePath) && path.contains(ignorePath)) {
            return;
        }

        File file = new File(path);
        if (!file.exists()) {
            return;
        }

        if (!file.isDirectory()) {
            try {
                file.delete();
            } catch (Exception e) {
                e.printStackTrace();
            }
            return;
        }

        File[] allFiles = file.listFiles();
        if (allFiles == null) {
            return;
        }
        for (File logFile : allFiles) {
            try {
                deleteDirAndFile(logFile.getAbsolutePath(), ignorePath);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    public static ArrayList<String> iteratorFile(String path) {
        if (!path.endsWith(File.separator)) {
            path = path + File.separator;
        }

        ArrayList<String> ret = new ArrayList<>();
        File file = new File(path);
        if (!file.isDirectory()) {
            ret.add(file.getAbsolutePath());
        }

        File[] allFiles = file.listFiles();
        if (allFiles == null) {
            return ret;
        }

        for (File logFile : allFiles) {
            ret.add(logFile.getAbsolutePath());
        }
        return ret;
    }


    private static final String TAG = FileOpUtil.class.getSimpleName();

    /**
     * 调用此方法自动计算指定文件或指定文件夹的大小
     *
     * @param filePath 文件路径
     * @return 计算好的带B、KB、MB、GB的字符串
     */
    public static String getDirAndFileWithFormatSize(String filePath, String ignorePath) {
        File file = new File(filePath);
        long blockSize = 0;
        try {
            if (file.isDirectory()) {
                blockSize = getDirSize(file, ignorePath);
            } else {
                blockSize = getFileSize(file, ignorePath);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return formatSize(blockSize);
    }

    /**
     * 获取指定文件大小
     *
     * @param file
     * @return
     * @throws Exception
     */
    private static long getFileSize(File file, String ignorePath) throws Exception {
        long size = 0;
        Log.d(TAG, "getFileSize  === " + file.getAbsolutePath());

        if (file.getAbsolutePath().contains(ignorePath)) {
            return 0;
        }

        if (file.exists()) {
            FileInputStream fis = null;
            fis = new FileInputStream(file);
            size = fis.available();
        } else {
            file.createNewFile();
        }
        return size;
    }

    /**
     * 获取指定文件夹
     *
     * @param f
     * @return
     * @throws Exception
     */
    private static long getDirSize(File f, String ignorePath) throws Exception {
        Log.d(TAG, "getDirSize  === " + f.getAbsolutePath());

        long size = 0;
        File flist[] = f.listFiles();
        for (int i = 0; i < flist.length; i++) {
            if (flist[i].isDirectory()) {
                size = size + getDirSize(flist[i], ignorePath);
            } else {
                size = size + getFileSize(flist[i], ignorePath);
            }
        }
        return size;
    }

    /**
     * 转换文件大小
     *
     * @param fileS
     * @return
     */
    private static String formatSize(long fileS) {
        DecimalFormat df = new DecimalFormat("#.00");
        String fileSizeString = "";
        String wrongSize = "0B";
        if (fileS == 0) {
            return wrongSize;
        }
        if (fileS < 1024) {
            fileSizeString = df.format((double) fileS) + "B";
        } else if (fileS < 1048576) {
            fileSizeString = df.format((double) fileS / 1024) + "KB";
        } else if (fileS < 1073741824) {
            fileSizeString = df.format((double) fileS / 1048576) + "MB";
        } else {
            fileSizeString = df.format((double) fileS / 1073741824) + "GB";
        }
        return fileSizeString;
    }

}
